const koa = require('koa')
const app = new koa()
// 静态资源配置
const path  =  require('path') 
const koaStatic = require('koa-static') 
app.use(koaStatic(path.join(__dirname, './uploads')))
const jwt = require('jsonwebtoken')
//处理post请求的参数
const bodyparser = require('koa-bodyparser')
app.use(bodyparser())
//处理路由接口
const koaRouter = require('koa-router')
const router = koaRouter()


const slideRouter =  require('./routes/slide') 
console.log(slideRouter,11)
// 引入mysql 连接数据库
const mysql    = require('mysql')
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'ncmusic'
})
connection.connect()
app.use(router.routes())
app.use(router.allowedMethods())

// 轮播图相关路由
app.use(slideRouter.routes())
app.use(slideRouter.allowedMethods())


const multer = require('koa-multer')
var storage = multer.diskStorage({
    // 文件最终存储的位置
    destination: function (req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) // 时间戳
        let fixStr = file.mimetype.split('/')[1]
        cb(null, file.fieldname + '-' + uniqueSuffix + '.' + fixStr)
    }
})
const upload = multer({ storage: storage })
//上传图片
router.post('/test', upload.any(['avatar']), async(ctx,) => {
    try{
        console.log(ctx.req.body.name,1)
        /* eslint-disable */
        const url =  path.join(__dirname, ctx.req.files[0].path)
        const filename = ctx.req.files[0].filename
        // 把文件信息写入到数据库中
        await new Promise((resolve, reject) => {
            connection.query('insert into slides set ?', {url, filename, status: 1}, (err, results) => {
                if(err) reject(err)
                resolve(results)
            })
        })
        ctx.body = {
            code: 1,
            msg: '上传成功'
        }
    }catch(e) {
        ctx.body = {
            code: 0,
            error: e.message
        }
    }
})

//注册
router.post('/register',async( ctx )=>{
    try {
        const {phone,password,email} = ctx.request.body
        console.log(phone,password ,email)
        const res = await new Promise((res,rej)=>{
            connection.query(`select * from users where phone=${phone}`,(err,results)=>{
                if(err) rej(err) 
                res(results)
            })
        })
        console.log(res)
        if(res.length===0){
            //可以注册
            await new Promise((resolve,reject)=>{
                connection.query('insert into users set?',{phone,password},(err,results)=>{
                    if(err) reject(err)
                    resolve(results)
                })
            })
            ctx.body={
                code:1,
                data:'注册成功'
            }
        }else{ 
            //已被注册
            ctx.body = {
                code :0,
                data:'已被注册'
            }
        }
    } catch (error) {
        ctx.body = {
            code :0,
            data:error
        }
    }
})
//登录接口
router.post('/login', async(ctx) => {
    try {
        const {phone,password} = ctx.request.body
        const userRes = await new Promise((resolve, reject) => {
            connection.query('select * from users where phone=? and password=?', [phone, password], (err, results) => {
                if (err) reject(err)
                resolve(results)
            })
        })
        if (userRes.length!==0) {
            let token = jwt.sign({phone},'haiwang',{expiresIn:'10h'})
            console.log(token,1)
            ctx.body = {
                code: 1,
                msg: '登陆成功',
                token:token
            }
        } else {
            ctx.body = {
                code: 1,
                msg: '账号密码错误'
            }
        }
    } catch (error) {
        console.log(error)
        ctx.body = {
            code: 0,
            msg: error
        }
    }


})

//注册工作人员账号
router.post('/worker/register',async( ctx )=>{
    try {
        const {phone,password,email} = ctx.request.body
        console.log(phone,password ,email)
        const res = await new Promise((res,rej)=>{
            connection.query(`select * from workers where phone=${phone}`,(err,results)=>{
                if(err) rej(err) 
                res(results)
            })
        })
        console.log(res)
        if(res.length===0){
            //可以注册
            await new Promise((resolve,reject)=>{
                connection.query('insert into workers set?',{phone,password},(err,results)=>{
                    if(err) reject(err)
                    resolve(results)
                })
            })
            ctx.body={
                code:1,
                data:'注册成功'
            }
        }else{ 
            //已被注册
            ctx.body = {
                code :0,
                data:'已被注册'
            }
        }
    } catch (error) {
        ctx.body = {
            code :0,
            data:error
        }
    }
})
//工作人员登录接口
router.post('/worker/login', async(ctx) => {
    try {
        const {phone,password} = ctx.request.body
        const userRes = await new Promise((resolve, reject) => {
            connection.query('select * from workers where phone=? and password=?', [phone, password], (err, results) => {
                if (err) reject(err)
                resolve(results)
            })
        })
        console.log(userRes)
        if (userRes.length!==0) {
            let token = jwt.sign({phone},'haotian',{expiresIn:'10h'})
            console.log(token,1)
            ctx.body = {
                code: 1,
                msg: '登陆成功',
                token:token
            }
        } else {
            ctx.body = {
                code: 1,
                msg: '账号密码错误'
            }
        }
    } catch (error) {
        ctx.body = {
            code: 0,
            msg: 1
        }
    }


})
//获取轮播图
router.get('/getslides', async(ctx) => {
    try {
        // 解析判断token是否合法
        // let token = ctx.request.header.authorization
        // console.log(token,111)
        // // 对token进行解密
        // let decoded = jwt.verify(token, 'haotian')
        // console.log(decoded)
        let result = await new Promise((resolve, reject) => {
            connection.query('select * from slides', (err, results) =>{
                if(err) reject(err)
                resolve(results)
            })
        })
        result = result.map((item,index) =>{
                return {
                    url: `http://localhost:5000/${item.filename}`,
                }
            })
        ctx.body = {
            code: 1,
            list: result
        }
    } catch(e) {
        console.log(e)
        ctx.body = {
            code: 0,
            error: e
        }
    }
})

//评论歌曲
router.post('/comments',async(ctx)=>{
    try {
        let {songID , comment} = ctx.request.body
        // 解析判断token是否合法
        let token = ctx.request.header.authorization
        console.log(token,111)
        // 对token进行解密
        let decoded = jwt.verify(token, 'haotian')
        //解密成功
        if(decoded.phone){
            const user = await new Promise((resolve, reject) =>{
                connection.query('select * from workers where phone=?', decoded.phone, (err, results) => {
                    if(err) reject(err)
                    resolve(results)
                })
            })
            console.log(user)
            if(user.length>0){
                //说明有用户
                await new Promise((resolve,reject)=>{
                    connection.query('insert into comments set?',{phone:decoded.phone ,songID,comment},(err,results)=>{
                        if(err) reject(err)
                        resolve(results)
                    })
                })
                ctx.body={
                    code:1,
                    msg:'评论成功'
                }
            }else{
                //没有用户
            }
        }
        
    } catch (error) {
        ctx.body = {
            code: 0,
            error: errore
        }
    }
})
//获取评论
router.get('/getComments',async (ctx)=>{
    try {
        let token = ctx.request.header.authorization
        console.log(token,111)                                                               
        let decoded = jwt.verify(token, 'haotian')
        if(decoded.phone){
            const result = await new Promise((resolve, reject) => {
                connection.query('select * from comments', (err, results) =>{
                    if(err) reject(err)
                    resolve(results)
                })
            })
            ctx.body = {
                code: 1,
                error: result
            }
        }
    } catch (error) {
        ctx.body = {
            code: 0,
            error: errore
        }
    }
})














//获取所有数据
// router.get('/getdata',async ( ctx, )=>{
//     try {
//         const res = await new Promise((res,rej)=>{
//             connection.query('select * from box',(err,results)=>{
//                 if(err) throw err
//                 res(results)
//             })
//         })
//         ctx.body = {
//             code :1,
//             data:res
//         }
//     } catch (error) {
//         ctx.body = {
//             code :0,
//             data:error
//         }
//     }
    
    
// })
// //查找作者
// router.get('/getdata/name',async ( ctx, )=>{
//     try {
//         const {name} =ctx.query
//         const res = await new Promise((res,rej)=>{
//             connection.query(`select * from box where name="${name}"`,(err,results)=>{
//                 if(err) throw err
//                 res(results)
//             })
//         })
        
//         ctx.body = {
//             code :1,
//             data:res
//         }
//     } catch (error) {
//         ctx.body = {
//             code :0,
//             data:error
//         }
//     }
    
// })



// //修改users的信息
// router.post('/updata',async (ctx ) =>{
//     try {
//         const { phone ,name} =ctx.request.body
//         console.log( phone ,name )
//         await new Promise((resolve,reject)=>{
//             connection.query('u one=?',[name,phone],(err,results)=>{
//                 if(err) reject(err)
//                 resolve(results)
//             })
//         })
//         ctx.body = {
//             code:1,
//             data:'修改成功'
//         }
//     } catch (error) {
//         ctx.body = {
//             code :0,
//             data:error
//         }
//     }
// })
// //删除users的信息
// router.post('/deleteUsers', async( ctx )=>{
//     try {
//         const {phone} = ctx.request.body
//         console.log(phone)
//         await new Promise((resolve,reject)=>{
//             connection.query('delet  from users where phone=?',[phone],(err,results)=>{
//                 if(err) reject(err)
//                 resolve(results)
//             })
//         })
//         ctx.body = {
//             code :1,
//             data:'删除成功'
//         }
//     } catch (error) {
//         ctx.body = {
//             code :0,
//             data:error
//         }
//     }
// })
// //模糊搜索
// router.get('/dim',async(ctx)=>{
    
//     try {
//         const {name} = ctx.request.query
//         console.log(name)
//         const res = await new Promise((resolve,reject)=>{
//             connection.query('select * from users where name like ?', `%${name}%` ,(err,results)=>{
//                 if(err) reject(err)
//                 resolve(results)
//             })
//         })
        
//         ctx.body = {
//             code :1,
//             data:res
//         }
//     } catch (error) {
//         ctx.body = {
//             code :0,
//             data:error
//         }
//     }
// })
// router.post('/login',async( ctx , next)=>{
//     console.log(ctx.request.body)
//     ctx.body = '登陆成功'
// })

// router.post('/upload', async(ctx, next) => {
//     // 拿前端传来的数据：是一些大数据
//     let boundary = '--' + ctx.request.headers['content-type'].split(';')[1].split('=')[1]
//     let buf = Buffer.alloc(0)
//     let bSize = Buffer.byteLength(boundary) // 分割线的字节长度

//     let bufIndexArr = [] // 所有buf的下标
//     ctx.req.on('data', (chunk) => {
//         buf = Buffer.concat([buf, chunk])
//     })
//     ctx.req.on('end', _ => {
//         fs.writeFileSync('./a.txt', buf)
//         // 根据分隔符去拆分数据
//         // Buffer.slice(startIndex, endIndex)
//         // indexOf返回的是第一个符合条件的下标
//         // console.log('下标', buf.indexOf(boundary))

//         // 所有buf的下标
       
//         console.log( buf.toString().split(bSize))
//         let arr =buf.toString().split(bSize)
//         fs.writeFileSync    ('./b.txt', JSON.stringify(buf.toString().split(bSize)))
//         // let buf1 =buf.slice(bSize)
//         // let buf2 =buf1.slice(0,buf1.indexOf(boundary))
//         // fs.writeFileSync('./b.txt', buf2) 


//         // let buf3 =buf.slice(buf.indexOf(buf2)+buf2.length)

//         // buf1 =buf3.slice(bSize)
//         // buf2 =buf1.slice(0,buf1.indexOf(boundary))
//         // fs.writeFileSync('./c.txt', buf2)

        
//     })
//     ctx.body = {
//                 code :0,
//                 data:'a'
//             }
// })


app.listen(5000,()=>{
    console.log('服务器已经启动')
})